package com.ethank.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.aliyun.ocr_api20210707.Client;
import com.aliyun.ocr_api20210707.models.VerifyVATInvoiceRequest;
import com.aliyun.ocr_api20210707.models.VerifyVATInvoiceResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.ethank.common.core.domain.AjaxResult;
import com.ethank.common.utils.StringUtils;
import com.ethank.system.Utils.BillUtil;
import com.ethank.system.enums.BillEnum;
import com.ethank.system.service.OcrService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Method;
import java.util.HashMap;


/**
 * @author Administrator
 */
@Service
public class OcrServiceImpl implements OcrService {

    private static final Logger logger = LoggerFactory.getLogger(OcrServiceImpl.class);
    @Value("${ocr.accessKeyId}")
    private String accessKeyId;

    @Value("${ocr.accessKeySecret}")
    private String accessKeySecret;

    /**
     * 发票数据获取
     *
     * @param file 文件
     * @return 返回
     */
    @Override

    public AjaxResult billUpload(MultipartFile file,Integer type) throws Exception {
        Long startTime = System.currentTimeMillis();
        BillUtil billUtil = new BillUtil();
        //查询识别类型对应的方法
        String apiInvoke = BillEnum.getInvokeName(type);
        Method declaredMethod = billUtil.getClass().getDeclaredMethod(apiInvoke, MultipartFile.class, String.class, String.class);
        Object invoke = declaredMethod.invoke(billUtil, file, accessKeyId, accessKeySecret);
        Long endTime = System.currentTimeMillis();
        System.out.println("========> 接口耗时：" + (endTime - startTime));
        return AjaxResult.success(JSONObject.parse(JSONObject.toJSONString(invoke)));
    }


//    /**
//     * 发票数据获取
//     *
//     * @param file 文件
//     * @return 返回
//     */
//    @Override
//    public AjaxResult billUpload(MultipartFile file) throws Exception {
//        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
//                // 必填，您的 AccessKey ID
//                .setAccessKeyId(accessKeyId)
//                // 必填，您的 AccessKey Secret
//                .setAccessKeySecret(accessKeySecret);
//        config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
//
//        Client client = new Client(config);
//
//
//        RecognizeMixedInvoicesRequest recognizeMixedInvoicesRequest = new RecognizeMixedInvoicesRequest();
//        RuntimeOptions runtime = new RuntimeOptions();
//
//        try {
//            byte[] byteArr = file.getBytes();
//            InputStream inputStream = new ByteArrayInputStream(byteArr);
//            recognizeMixedInvoicesRequest.setBody(inputStream);
//            // 复制代码运行请自行打印 API 的返回值
//            RecognizeMixedInvoicesResponse recognizeMixedInvoicesResponse =
//                    client.recognizeMixedInvoicesWithOptions(recognizeMixedInvoicesRequest, runtime);
//            String data = recognizeMixedInvoicesResponse.getBody().getData();
//            JSONObject jo = JSON.parseObject(data);
//            JSONArray subMsgs = jo.getJSONArray("subMsgs");
//            ArrayList<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
//            System.out.println("所有识别后的数据 -----> {}" + subMsgs);
//            // 遍历每一个
//            subMsgs.forEach(e -> {
//                System.out.println("每一条数据 -----> {}" + e);
//                HashMap<String, Object> resultMap = new HashMap<>();
//                JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(e));
//                JSONObject result1 = jsonObject.getJSONObject("result");
//                JSONObject data1 = result1.getJSONObject("data");
//
//                // 装载数据
//                resultMap.put("index", jsonObject.get("index"));
//                resultMap.put("op", jsonObject.get("op"));
//                resultMap.put("type", jsonObject.get("type"));
//                resultMap.put("data", data1);
//                maps.add(resultMap);
//                System.out.println("------------");
//            });
//            return AjaxResult.success(maps);
//        } catch (TeaException error) {
//            // 错误 message
//            System.out.println(error.getMessage());
//            // 诊断地址
//            System.out.println(error.getData().get("Recommend"));
//            com.aliyun.teautil.Common.assertAsString(error.message);
//        } catch (Exception _error) {
//            TeaException error = new TeaException(_error.getMessage(), _error);
//            // 错误 message
//            System.out.println(error.getMessage());
//            // 诊断地址
//            System.out.println(error.getData().get("Recommend"));
//            com.aliyun.teautil.Common.assertAsString(error.message);
//        }
//        return AjaxResult.error();
//    }


    @Override
    public AjaxResult verifyInvoice(String invoiceNo, String invoiceDate) {
        if (StringUtils.isBlank(invoiceNo) || StringUtils.isBlank(invoiceNo)) {
            return AjaxResult.error("请求发票号或开票日期不可为空");
        }
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        VerifyVATInvoiceRequest verifyVATInvoiceRequest = new VerifyVATInvoiceRequest().setInvoiceNo(invoiceNo).setInvoiceDate(invoiceDate);
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            Client client = new Client(config);

            VerifyVATInvoiceResponse verifyVATInvoiceResponse =   client.verifyVATInvoiceWithOptions(verifyVATInvoiceRequest, runtime);
            logger.error("发票核验结果=>"+verifyVATInvoiceResponse.getBody().toString());
            JSONObject jsonObject = JSONObject.parseObject(verifyVATInvoiceResponse.getBody().getData());
            HashMap<String, Object> resultMap = new HashMap<>(2);
            //请求响应code=001成功,其余code视为核验失败
            String code = jsonObject.getString("code");
            //返回响应 0-失败 1-成功
            resultMap.put("checkResult",0);
            if(StringUtils.isNotBlank(code) && code.equals("001")){
                resultMap.put("checkResult",1);
            }
            String msg = jsonObject.getString("msg");
            resultMap.put("msg",msg);
            return AjaxResult.success(resultMap);

        } catch (Exception _error) {
            logger.error(_error.getMessage());
        }
        return AjaxResult.error();
    }


}
